package com.dmyang.service.impl;

import com.dmyang.common.pojo.BootstrapTableResult;
import com.dmyang.common.pojo.HyResult;
import com.dmyang.dao.HyTagMapper;
import com.dmyang.entity.HyTag;
import com.dmyang.entity.HyTagExample;
import com.dmyang.service.TagService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 标签管理Service
 * Created by brss on 2017/8/6.
 */
@Service("tagServiceImpl")
public class TagServiceImpl implements TagService {

    @Autowired
    private HyTagMapper tagMapper;

    /**
     * 列出所有标签（分页）
     * @param offset
     * @param limit
     * @return
     */
    @Override
    public BootstrapTableResult showTagList(Integer offset, Integer limit) {
        //计算起始页
        Integer page = (offset/limit) + 1;
        HyTagExample example = new HyTagExample();
        //分页
        PageHelper.startPage(page,limit);
        List<HyTag> list = tagMapper.selectByExample(example);
        //获取总条数
        PageInfo<HyTag> info = new PageInfo<>(list);
        BootstrapTableResult result = new BootstrapTableResult(info.getTotal(), list);
        return result;
    }

    /**
     * 新增一个标签
     * @param tag
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public HyResult addTag(HyTag tag) throws Exception {
        tagMapper.insertSelective(tag);
        return HyResult.build(200,"新增成功！");
    }

    /**
     * 修改一个分类
     * @param tag
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public HyResult modifyTag(HyTag tag) throws Exception {
        tagMapper.updateByPrimaryKeySelective(tag);
        return HyResult.build(200,"修改成功！");
    }

    /**
     * 删除分类（可同时删除多条，用逗号隔开）
     * @param ids
     * @return
     * @throws Exception
     */
    @Transactional
    @Override
    public HyResult deleteTag(String ids) throws Exception {
        if (ids.contains(",")) {
            //多条删除
            String[] split = ids.split(",");
            for (String id : split) {
                tagMapper.deleteByPrimaryKey(Integer.parseInt(id));
            }
        }else {
            tagMapper.deleteByPrimaryKey(Integer.parseInt(ids));
        }
        return HyResult.build(200,"删除成功");
    }

}
